import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ReportsService} from "../reports.service";
import {ConfirmationService, SelectItem} from "primeng/primeng";

@Component({
  selector: 'app-send-config',
  templateUrl: './send-config.component.html',
  styleUrls: ['./send-config.component.css']
})
export class SendConfigComponent implements OnInit {
  display;
  title;
  config: FormGroup;
  @Input() currentCon;
  @Input() state;
  @Output() closeConfigEdit = new EventEmitter();
  @Output() addCon = new EventEmitter();
  @Output() updateCon = new EventEmitter();
  ch;
  dayShow;
  monthShow;
  yearShow;
  weekShow;
  type;
  week;
  weekTime;
  dayTime;
  monthTime;
  yearTime;
  sendWay = [];
  weeks: SelectItem[];
  names = [];
  receivers = [];
  enable = [];
  templates = [];
  persons = [];
  submitAddCon = {//新增发送配置参数
    "names": [],
    "types": [],
    "send_time": "",
    "week_send_time": "",
    "send_way":  "",
    "receivers": [],
    "addrs": [],
    // "urls": [],
    "tids": [],
    "enable": false
  };
  submitEditCon = {//编辑发送配置参数
    "sid": "",
    "names": [],
    "types": [],
    "send_time": "",
    "week_send_time": "",
    "send_way":  "",
    "receivers": [],
    "addrs": [],
    // "urls": [],
    "tids": [],
    "enable": false
  };

  constructor(
    private fb: FormBuilder,
    private reportsService: ReportsService,
    private confirmationService: ConfirmationService,
    ) {
    this.config = fb.group({
      names: ["", Validators.required],
      send_way: ["", Validators.required],
      type: ["", Validators.required],
      way: ["", Validators.required],
      dayTime: [""],
      monthTime: [""],
      yearTime: [""],
      week: [""],
      weekTime: [""],
      enable: ["", Validators.required],
      receivers: ["", Validators.required],
    })
  }

  ngOnInit() {
    console.log(this.currentCon)
    this.display = true;
    if(this.state == "add"){
      this.title = "新增发送配置";
      this.sendWay = ["email"];
      this.dayShow = true;
    }else {
      this.title = "修改发送配置";
      // this.submitEditCon.sid = this.currentCon.sid;
      for (let i = 0, len = this.currentCon.names.length;i < len;i++){
        this.names.push(
          {text:this.currentCon.names[i],name:this.currentCon.names[i],sid:this.currentCon.tids[i],type:this.currentCon.types[i]}
        )
      }
      this.sendWay = [this.currentCon.send_way];
      this.type = this.currentCon.types[0];
      this.showWhichDate();
      if(this.type == "week"){
        this.week = this.currentCon.week_send_time.split(" ")[0];
        this.weekTime = this.currentCon.week_send_time.split(" ")[1];
      }else {
        this.dayTime = this.currentCon.send_time;
        this.monthTime = new Date(new Date().getFullYear() + "-" + (new Date().getMonth() + 1) + "-" + this.currentCon.send_time);
        this.yearTime = this.currentCon.send_time;
      }
      for (let i = 0, len = this.currentCon.receivers.length;i < len;i++){
        this.receivers.push(
          {text:this.currentCon.receivers[i],name:this.currentCon.receivers[i],url:this.currentCon.tids[i]}
        )
      }
      this.enable = [this.currentCon.enable + ""];
    }
    this.ch = {
      firstDayOfWeek: 0,
      dayNames: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"],
      dayNamesShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      dayNamesMin: ["日", "一", "二", "三", "四", "五", "六"],
      monthNames: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
      monthNamesShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
    };
    this.weeks = [
      {label:"周一", value: "Mon"},
      {label:"周二", value: "Tues"},
      {label:"周三", value: "Wed"},
      {label:"周四", value: "Thurs"},
      {label:"周五", value: "Fri"},
      {label:"周六", value: "Sat"},
      {label:"周日", value: "Sun"},
    ];
  }

  //查询报表
  searchTemps(event) {
    let dataParam = {
      "sids": [],
      "sheet": [],
      "name": event.query,
      "enable": true
    };
    this.reportsService.getReportTemplets(dataParam).subscribe(data => {
      // console.log(data)
      this.templates = data;
    });
  }

  //选中某一报表
  selectTemp(event){
    let repeatFlag = this.isRepeat(this.names);
    if (!repeatFlag) {//不同类型的模板
      this.names.pop();  //从类型数组将此条内容删除
    }
    this.type = this.names[0].type;
    this.showWhichDate();
  }

  //判断数组中是否存在不同的元素
  isRepeat (arr) {
    let types = arr.sort();
    for (let i = 0; i < types.length-1; i++) {
      if (types[i].type != types[i+1].type) {
        alert("请选择相同类型的模板!");
        return false;
      };
    };
    return true;
  }

  searchPersons(event) {
    this.reportsService.getPersons(event.query).subscribe(data => {
      // console.log(data)
      this.persons = data;
    });
  }

  //保存
  formSubmit(bool){
    if (this.state == "add"){
      this.submitAddCon = this.createSubmitParam();
      this.addSendCon(bool);
    }else {
      this.submitEditCon = this.createSubmitParam();
      this.updateSendCon(bool);
    }
  }

  //新增发送配置
  addSendCon(bool){
    this.reportsService.addSendCon(this.submitAddCon).subscribe(()=>{
      this.addCon.emit(bool);
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }

  //修改发送配置
  updateSendCon(bool){
    console.log(this.submitEditCon);
    this.reportsService.updateSendCon(this.submitEditCon).subscribe(()=>{
      this.updateCon.emit(this.currentCon);
      this.closeConfigEdit.emit(bool);
    })
  }

  //构建编辑发送配置参数
  createSubmitParam(){
    let submitParam = {
      "sid":"",
      "names": [],
      "types": [],
      "send_time": "",
      "week_send_time": "",
      "send_way":  "",
      "receivers": [],
      "addrs": [],
      // "urls": [],
      "tids": [],
      "enable": false
    };
    if (this.currentCon.sid){
      submitParam.sid = this.currentCon.sid;
    }
    for (let i = 0, len = this.config.value.names.length;i < len;i++){
      submitParam.names.push(this.config.value.names[i].name);
      submitParam.tids.push(this.config.value.names[i].sid);
      submitParam.types.push(this.config.value.names[i].type);
    }
    if(this.names[0].type == "week"){
      submitParam.send_time = "";
      submitParam.week_send_time = this.config.value.week + " " + this.config.value.weekTime;
    }else{
      submitParam.week_send_time = "";
      if(this.names[0].type == "day"){
        submitParam.send_time = this.config.value.dayTime;
      }else if(this.names[0].type == "month"){
        submitParam.send_time = this.config.value.monthTime;
      }if(this.names[0].type == "year"){
        submitParam.send_time = this.config.value.yearTime;
      }else {

      }
    }

    submitParam.send_way = this.config.value.send_way.length == 1 ? this.config.value.send_way[0] : this.config.value.send_way;
    for (let i = 0, len = this.config.value.receivers.length;i < len;i++){
      submitParam.receivers.push(this.config.value.receivers[i].name);
      submitParam.addrs.push(this.config.value.receivers[i].addr);
    }
    if (this.enable.length){
      submitParam.enable = true;
    }else {
      submitParam.enable = false;
    }
    return submitParam;
  }

  //判断显示哪个日期选择器
  showWhichDate(){
    if(this.type == "week"){//周报
      this.weekShow = true;
      this.dayShow = false;
      this.monthShow = false;
      this.yearShow = false;
    }else if(this.type == "day"){//日报
      this.dayShow = true;
      this.weekShow = false;
      this.monthShow = false;
      this.yearShow = false;
    }else if(this.type == "month"){//月报
      this.monthShow = true;
      this.weekShow = false;
      this.dayShow = false;
      this.yearShow = false;
    }else if(this.type == "year"){//年报
      this.yearShow = true;
      this.weekShow = false;
      this.dayShow = false;
      this.monthShow = false;
    }else {//其他

    }
  }

  closeConEditMask(bool){
    this.closeConfigEdit.emit(bool);
  }

}
